const app = getApp()
import Palette from '../utils/palette.js'
import {
  rgbToHex
} from '../utils/util.js'

Page({
  data: {
    imgData: [],
    imgBg: "#efefef",
    indicatorDots: true,
    autoplay: true,
    current: 0,
    interval: 3000,
    duration: 1000,
  },
  onReady() {
    this.fetchImageData();
  },
  fetchImageData() {
    let imgUrls = [
      'http://cos.jzworks.cn/palette1.png',
      'http://cos.jzworks.cn/palette2.png',
      'http://cos.jzworks.cn/palette3.png',
      'http://cos.jzworks.cn/palette4.png',
      'http://cos.jzworks.cn/palette5.png',
      'http://cos.jzworks.cn/palette6.png'
    ];
    Promise.all(imgUrls.map(url => {
      return new Promise((resolve, reject) => {
        wx.getImageInfo({
          src: url,
          success: (res) => {
            resolve({
              url: url,
              path: res.path,
              palette: ''
            });
          }
        })
      })
    })).then(resArr => {
      this.setData({
        imgData: resArr
      })
      this.getPalette(0)
    })
  },
  onChange(e) {
    let current = e.detail.current
    this.setData({
      current: current
    })
    this.getPalette(current);
  },
  getPalette(current) {
    let currentItem = this.data.imgData[current]
    if (!currentItem.palette) {
      let canvasId = 'canvas'
      let ctx = wx.createCanvasContext(canvasId)
      let width = 150,
        height = 100;
      wx.getImageInfo({
        src: this.data.imgData[current].path,
        success: (res) => {
          new Palette(canvasId).getPalette({
            width: width,
            height: height,
            imgPath: res.path,
            colorCount: 3,
            quality: 1
          }, (colors) => {
            if (colors) {
              colors = colors.map((color) => {
                return ('#' + rgbToHex(color[0], color[1], color[2]))
              })
              let item = 'imgData[' + current + '].palette'
              let palette = colors[1]
              this.setData({
                [item]: colors[1],
                imgBg: palette
              })
            }
          });
        }
      })
    } else {
      this.setData({
        imgBg: currentItem.palette
      })
    }
  }
})